package com.sxyc.config;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.cron4j.Cron4jPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.render.ViewType;
import com.jfinal.template.Engine;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.sxyc.config.routes.AdminRoutes;
import com.sxyc.config.routes.WebRoutes;
import com.sxyc.config.routes.WeiXinRoutes;
import com.sxyc.plugin.SchedulerPlugin;
import com.sxyc.tintin.model.Address;
import com.sxyc.tintin.model.CarInfo;
import com.sxyc.tintin.model.Chongzhi;
import com.sxyc.tintin.model.Device;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.tintin.model.Drivingrange;
import com.sxyc.tintin.model.FeedBack;
import com.sxyc.tintin.model.HideTrack;
import com.sxyc.tintin.model.MediaUpload;
import com.sxyc.tintin.model.Person;
import com.sxyc.tintin.model.WxConfig;
import com.sxyc.tintin.model.WxUser;
import com.sxyc.tintin.model.XnNet;
import com.sxyc.tintin.sdk.SDKUtils;

/**
 * @author Javen
 */
public class AppConfig extends JFinalConfig {

	// 使用jFinal 日志
	private com.jfinal.log.Log log = com.jfinal.log.Log.getLog(this.getClass());
	// 使用Log4j（需要配置：log4j.properties）
	private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(this.getClass());

	/**
	 * 如果生产环境配置文件存在，则优先加载该配置，否则加载开发环境配置文件
	 * 
	 * @param pro
	 *            生产环境配置文件
	 * @param dev
	 *            开发环境配置文件
	 */
	public void loadProp(String pro, String dev) {
		try {
			PropKit.use(pro);
		} catch (Exception e) {
			PropKit.use(dev);
		}
	}

	/**
	 * 配置常量
	 */
	public void configConstant(Constants me) {
		// 加载少量必要配置，随后可用PropKit.get(...)获取值
		loadProp("appConfig.properties", "appConfig.properties");
		me.setDevMode(PropKit.getBoolean("devMode", false));
		me.setEncoding("UTF-8");
		me.setViewType(ViewType.JSP);
		// 设置上传文件保存的路径
		me.setBaseUploadPath(PathKit.getWebRootPath() + File.separator + "Upload");
		// ApiConfigKit 设为开发模式可以在开发阶段输出请求交互的 xml 与 json 数据
		ApiConfigKit.setDevMode(me.getDevMode());
	}

	/**
	 * 配置路由
	 */
	public void configRoute(Routes me) {
		me.add(new WeiXinRoutes());
		me.add(new WebRoutes());
		me.add(new AdminRoutes());
	}


	/**
	 * 配置 Template Engine
	 */
	public void configEngine(Engine arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 配置插件
	 */
	public void configPlugin(Plugins me) {
		// 配置DruidPlugin插件
		String jdbcUrl = PropKit.get("jdbcUrl");
		String user = PropKit.get("user");
		String password = PropKit.get("password");
		log.info(jdbcUrl + " " + user + " " + password);
		DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, user, password);
		druidPlugin.addFilter(new StatFilter());// 配置druid监控
		WallFilter wall = new WallFilter();
		wall.setDbType("mysql");
		druidPlugin.addFilter(wall);
		me.add(druidPlugin);

		// 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		// 配置属性名(字段名)大小写不敏感容器工厂  
		arp.setContainerFactory(new CaseInsensitiveContainerFactory()); 
		arp.addMapping("ChongZhi", "Id", Chongzhi.class);
		arp.addMapping("DeviceInfo", "Id", Device.class);
		arp.addMapping("DeviceBinding", "Id", DeviceBinding.class);
		arp.addMapping("Wx_Config", "Id", WxConfig.class);
		arp.addMapping("Wx_User", "Id", WxUser.class);
		arp.addMapping("person", "pid", Person.class);
		arp.addMapping("MediaUpload", "Id", MediaUpload.class);
		arp.addMapping("address", "Id", Address.class);
		arp.addMapping("carinfo", "Id",CarInfo.class);
		arp.addMapping("HideTrack", "Id",HideTrack.class);
		arp.addMapping("drivingrange", "Id",Drivingrange.class);
		arp.addMapping("feedback", "Id",FeedBack.class);
		arp.addMapping("xnnet", "Id",XnNet.class);
		arp.setShowSql(PropKit.getBoolean("devMode", false));
		me.add(arp);

		// EhCache插件配置
		EhCachePlugin cachePlugin = new EhCachePlugin();
		me.add(cachePlugin);

		// Redis插件配置
		String redisName = PropKit.use("redis.properties").get("redisName");
		String redisHost = PropKit.use("redis.properties").get("redisHost");
		int redisPort = PropKit.use("redis.properties").getInt("redisPort");
		RedisPlugin redisPlugin = new RedisPlugin(redisName, redisHost, redisPort);
		me.add(redisPlugin);
		
		// 定时任务插件加载
		SchedulerPlugin sp = new SchedulerPlugin("job.properties");
		me.add(sp);
		
		Cron4jPlugin cp = new Cron4jPlugin("appConfig.properties");
		me.add(cp);
	}

	/**
	 * 配置全局拦截器
	 */
	public void configInterceptor(Interceptors me) {

	}

	/**
	 * 配置处理器
	 */
	public void configHandler(Handlers me) {
		// Druid监控
		DruidStatViewHandler dvh = new DruidStatViewHandler("/druid", new IDruidStatViewAuth() {

			@Override
			public boolean isPermitted(HttpServletRequest request) {
				return true;
			}
		});
		me.add(dvh);
	}

	@Override
	public void afterJFinalStart() {
		super.afterJFinalStart();
		
		log.info("JFinal Start Complete ...");
		
		//启动Service
		SDKUtils.start();
		
		//初始化Service
//		SDKUtils.init();
		
		//初始化其他
//		SDKUtils.initOther();
		
	}

	@Override
	public void beforeJFinalStop() {
		super.beforeJFinalStop();
		
		log.info("JFinal Stop Complete ...");
	}

	/**
	 * 建议使用 JFinal 手册推荐的方式启动项目 运行此 main
	 * 方法可以启动项目，此main方法可以放置在任意的Class类定义中，不一定要放于此
	 */
	public static void main(String[] args) {
		JFinal.start("src/main/webapp", 8080, "/", 5);// 启动配置项
	}
	
}
